<template>
	<view 
		class="schedule-card"
		:class="[
			`priority-${schedule.priority}`,
			{ 
				completed: schedule.completed, 
				overdue: isOverdue,
				'completing': isCompleting,
				'fade-out': shouldFadeOut,
				'swiped': showActions
			}
		]"
		@touchstart="handleTouchStart"
		@touchmove="handleTouchMove"
		@touchend="handleTouchEnd"
		@longtap="handleLongPress"
	>
		<!-- 完成动画进度条 -->
		<view 
			class="completion-progress" 
			:class="{ active: isCompleting }"
			:style="{ width: progressWidth + '%' }"
		></view>
		
		<!-- 固定内容层（不移动） -->
		<view class="fixed-content">
			<!-- 日程主要内容 -->
			<view class="content-main">
				<text class="schedule-title" :class="{ completed: schedule.completed }">
					{{ schedule.title }}
				</text>
				<view class="description" v-if="schedule.description">
					<text class="description-text">{{ schedule.description }}</text>
				</view>
			</view>
			
			<!-- 时间信息显示 -->
			<view class="time-info-fixed">
				<uni-icons 
					:type="schedule.type === 'task' ? 'checkbox' : 'calendar'" 
					size="14" 
					:color="timeColor" 
				/>
				<text class="time-text" :style="{ color: timeColor }">
					{{ schedule.type === 'task' ? '无时间限制' : formatTime(schedule.endTime) }}
				</text>
				<text v-if="isOverdue && schedule.type !== 'task'" class="overdue-text">已过期</text>
			</view>
		</view>
		
		<!-- 可移动元素层（滑动时移动） -->
		<view class="movable-elements" :style="{ transform: `translateX(${translateX}px)` }">
			<!-- 左侧优先级指示边框 -->
			<view class="priority-border"></view>
			
			<!-- 标签显示区域 -->
			<view class="tags-container" v-if="schedule.tags && schedule.tags.length > 0">
				<text 
					v-for="tag in schedule.tags" 
					:key="tag" 
					class="tag"
				>
					{{ tag }}
				</text>
			</view>
			
			<!-- 底部元信息 -->
			<view class="meta-info-container">
				<!-- 类型标签 -->
				<view class="type-tag" :class="schedule.type">
					<text class="type-text">{{ schedule.type === 'task' ? '任务' : '日程' }}</text>
				</view>
				<!-- 优先级标签 -->
				<view class="priority-tag" :class="`priority-${schedule.priority}`">
					<text class="priority-text">{{ getPriorityText(schedule.priority) }}</text>
				</view>
			</view>
		</view>
		
		<!-- 右侧操作按钮（滑动显示） -->
		<view class="card-actions" :class="{ visible: showActions }">
			<button class="action-btn edit-btn" @click.stop="editSchedule">
				<uni-icons type="compose" size="16" color="#FFFFFF" />
			</button>
			<button class="action-btn delete-btn" @click.stop="deleteSchedule">
				<uni-icons type="trash" size="16" color="#FFFFFF" />
			</button>
		</view>
	</view>
</template>

<script>
/**
 * 日程卡片组件
 * 支持滑动操作、长按完成、优先级显示等功能
 */
export default {
	name: 'ScheduleCard',
	
	props: {
		/** 日程数据对象 */
		schedule: {
			type: Object,
			required: true
		}
	},
	
	data() {
		return {
			// ========== 界面状态 ==========
			/** 是否显示操作按钮 */
			showActions: false,
			/** 是否正在完成（长按动画） */
			isCompleting: false,
			/** 是否应该淡出（完成后） */
			shouldFadeOut: false,
			/** 完成进度条宽度百分比 */
			progressWidth: 0,
			
			// ========== 定时器 ==========
			/** 长按定时器 */
			longPressTimer: null,
			/** 进度条定时器 */
			progressTimer: null,
			
			// ========== 滑动相关 ==========
			/** 触摸开始X坐标 */
			startX: 0,
			/** 触摸开始Y坐标 */
			startY: 0,
			/** 是否正在移动 */
			isMoving: false,
			/** 滑动阈值，超过这个距离才显示操作按钮 */
			threshold: 60,
			/** 可移动元素的X轴位移 */
			translateX: 0,
			
			// ========== 长按相关 ==========
			/** 长按开始时间 */
			longPressStartTime: 0,
			/** 长按持续时间（毫秒） */
			longPressDuration: 1500,
			/** 是否正在长按 */
			isLongPressing: false
		}
	},
	
	computed: {
		/**
		 * 是否过期
		 * 任务类型永不过期，已完成的也不算过期
		 * @returns {boolean}
		 */
		isOverdue() {
			if (this.schedule.completed || this.schedule.type === 'task') return false
			const now = new Date()
			const deadline = new Date(this.schedule.endTime)
			return deadline < now
		},
		
		/**
		 * 时间文字颜色
		 * 根据完成状态、过期状态和剩余时间确定颜色
		 * @returns {string} 颜色值
		 */
		timeColor() {
			if (this.schedule.completed) return '#10B981'  // 绿色 - 已完成
			if (this.isOverdue) return '#EF4444'           // 红色 - 已过期
			
			const now = new Date()
			const deadline = new Date(this.schedule.endTime)
			const diffHours = (deadline - now) / (1000 * 60 * 60)
			
			if (diffHours < 24) return '#F59E0B'  // 橙色 - 24小时内
			return '#6B7280'                      // 灰色 - 正常
		}
	},
	
	methods: {
		// ========== 时间格式化 ==========
		/**
		 * 格式化时间显示
		 * @param {string} timeString - ISO时间字符串
		 * @returns {string} 格式化后的时间文本
		 */
		formatTime(timeString) {
			const date = new Date(timeString)
			const now = new Date()
			
			// 获取日期部分（忽略时间）
			const dateOnly = new Date(date.getFullYear(), date.getMonth(), date.getDate())
			const nowOnly = new Date(now.getFullYear(), now.getMonth(), now.getDate())
			const diffDays = Math.round((dateOnly - nowOnly) / (1000 * 60 * 60 * 24))
			
			const timeStr = `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
			
			// 今天
			if (diffDays === 0) {
				return `今天 ${timeStr}`
			}
			// 明天
			else if (diffDays === 1) {
				return `明天 ${timeStr}`
			}
			// 昨天
			else if (diffDays === -1) {
				return `昨天 ${timeStr}`
			}
			// 其他日期
			else {
				const month = (date.getMonth() + 1).toString().padStart(2, '0')
				const day = date.getDate().toString().padStart(2, '0')
				return `${month}/${day} ${timeStr}`
			}
		},
		
		/**
		 * 获取优先级显示文本
		 * @param {string} priority - 优先级值
		 * @returns {string} 优先级文本
		 */
		getPriorityText(priority) {
			const map = {
				'urgent': '紧急',
				'high': '高',
				'medium': '中',
				'low': '低'
			}
			return map[priority] || '中'
		},
		
		// ========== 触摸事件处理 ==========
		/**
		 * 触摸开始事件处理
		 * @param {TouchEvent} e - 触摸事件
		 */
		handleTouchStart(e) {
			this.startX = e.touches[0].clientX
			this.startY = e.touches[0].clientY
			this.isMoving = true
			
			// 如果没有完成且没有显示操作按钮，开始长按检测
			if (!this.schedule.completed && !this.showActions) {
				this.startLongPress()
			}
		},
		
		/**
		 * 触摸移动事件处理
		 * @param {TouchEvent} e - 触摸事件
		 */
		handleTouchMove(e) {
			if (!this.isMoving) return
			
			const currentX = e.touches[0].clientX
			const currentY = e.touches[0].clientY
			const deltaX = currentX - this.startX
			const deltaY = currentY - this.startY
			
			// 如果有移动，取消长按
			if (Math.abs(deltaX) > 10 || Math.abs(deltaY) > 10) {
				this.cancelLongPress()
			}
			
			// 如果垂直滑动距离大于水平滑动距离，则不处理（让页面正常滚动）
			if (Math.abs(deltaY) > Math.abs(deltaX)) {
				this.isMoving = false
				return
			}
			
			// 阻止默认事件，防止页面滚动
			e.preventDefault()
			
			// 实时更新可移动元素的位置
			if (deltaX < 0) {
				// 向左滑动，限制最大滑动距离
				this.translateX = Math.max(deltaX, -120)
			} else if (this.showActions && deltaX > 0) {
				// 如果已经显示操作按钮，允许向右滑动收回
				this.translateX = Math.min(deltaX - 120, 0)
			}
		},
		
		/**
		 * 触摸结束事件处理
		 * @param {TouchEvent} e - 触摸事件
		 */
		handleTouchEnd(e) {
			if (!this.isMoving) return
			this.isMoving = false
			
			// 取消长按
			this.cancelLongPress()
			
			// 根据滑动距离决定最终状态
			if (Math.abs(this.translateX) > this.threshold) {
				// 滑动距离超过阈值，显示操作按钮
				this.showActions = true
				this.translateX = -120
			} else {
				// 滑动距离不足，恢复原位
				this.showActions = false
				this.translateX = 0
			}
		},
		
		// ========== 长按功能 ==========
		/**
		 * 开始长按操作
		 * 启动进度条动画
		 */
		startLongPress() {
			this.isLongPressing = true
			this.isCompleting = true
			this.progressWidth = 0
			this.longPressStartTime = Date.now()
			
			// 启动进度条动画（60fps）
			this.progressTimer = setInterval(() => {
				const elapsed = Date.now() - this.longPressStartTime
				const progress = Math.min((elapsed / this.longPressDuration) * 100, 100)
				this.progressWidth = progress
				
				if (progress >= 100) {
					this.completeLongPress()
				}
			}, 16)
		},
		
		/**
		 * 取消长按操作
		 * 清理进度条和定时器
		 */
		cancelLongPress() {
			if (this.isLongPressing) {
				this.isLongPressing = false
				this.isCompleting = false
				this.progressWidth = 0
				
				if (this.progressTimer) {
					clearInterval(this.progressTimer)
					this.progressTimer = null
				}
			}
		},
		
		/**
		 * 完成长按操作
		 * 触发完成事件和隐藏动画
		 */
		completeLongPress() {
			this.isLongPressing = false
			
			if (this.progressTimer) {
				clearInterval(this.progressTimer)
				this.progressTimer = null
			}
			
			// 保持进度条满状态一会儿
			setTimeout(() => {
				this.isCompleting = false
				this.shouldFadeOut = true
				this.progressWidth = 0
				
				// 触发完成事件
				this.$emit('toggle-completed', this.schedule.id)
				
				// 延迟隐藏，让用户看到完成效果
				setTimeout(() => {
					this.$emit('hide-completed', this.schedule.id)
				}, 800)
			}, 300)
		},
		
		/**
		 * 处理系统长按事件（备用）
		 * 当系统级长按触发时的处理
		 */
		handleLongPress() {
			if (!this.schedule.completed && !this.showActions && !this.isLongPressing) {
				this.startLongPress()
			}
		},
		
		// ========== 操作按钮 ==========
		/**
		 * 编辑日程
		 * 触发编辑事件并重置滑动状态
		 */
		editSchedule() {
			this.$emit('edit', this.schedule)
			this.resetSwipe()
		},
		
		/**
		 * 删除日程
		 * 触发删除事件并重置滑动状态
		 */
		deleteSchedule() {
			this.$emit('delete', this.schedule.id)
			this.resetSwipe()
		},
		
		/**
		 * 重置滑动状态
		 * 隐藏操作按钮并重置位移
		 */
		resetSwipe() {
			this.showActions = false
			this.translateX = 0
		}
	},
	
	/**
	 * 组件销毁时清理定时器
	 * 防止内存泄漏
	 */
	beforeDestroy() {
		this.cancelLongPress()
	}
}
</script>

<style lang="scss" scoped>
.schedule-card {
	position: relative;
	background-color: $card-white;
	border-radius: $border-radius-md;
	margin-bottom: $spacing-md;
	overflow: hidden;
	box-shadow: $shadow-sm;
	transition: all 0.3s ease;
	
	&:active {
		transform: scale(0.98);
	}
	
	&.completed {
		opacity: 0.8;
		
		.schedule-title {
			text-decoration: line-through;
		}
	}
	
	&.completing {
		.completion-progress {
			opacity: 0.9;
		}
	}
	
	&.fade-out {
		opacity: 0;
		transform: scale(0.95);
		transition: all 0.8s ease-out;
	}
	
	&.overdue:not(.completed) {
		border-left-color: $urgent-red;
		
		.priority-border {
			background-color: $urgent-red;
		}
	}
}

.completion-progress {
	position: absolute;
	top: 0;
	left: 0;
	height: 100%;
	width: 0;
	background: linear-gradient(90deg, #10B981, #34D399);
	z-index: 1;
	opacity: 0;
	transition: width 0.1s linear, opacity 0.2s ease;
}



.fixed-content {
	padding: $spacing-lg;
	margin-left: 4px; // 为左边框留空间
	position: relative;
	z-index: 2;
}

.content-main {
	margin-bottom: $spacing-md;
}

.schedule-title {
	font-size: $font-size-title-2;
	font-weight: $font-weight-semibold;
	color: $text-dark-gray;
	line-height: $line-height-title-2;
	display: block;
	margin-bottom: $spacing-xs;
}

.description {
	margin-bottom: $spacing-md;
}

.description-text {
	font-size: $font-size-body;
	color: $text-light-gray;
	line-height: $line-height-body;
}

.time-info-fixed {
	display: flex;
	align-items: center;
	gap: $spacing-xs;
}

.time-text {
	font-size: $font-size-caption;
	font-weight: $font-weight-normal;
}

.overdue-text {
	font-size: $font-size-caption;
	color: $urgent-red;
	font-weight: $font-weight-semibold;
	margin-left: $spacing-xs;
}

.movable-elements {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	pointer-events: none; // 防止阻挡固定内容的点击
	transition: transform 0.3s ease;
	z-index: 1;
}

.priority-border {
	position: absolute;
	left: 0;
	top: 0;
	bottom: 0;
	width: 4px;
	z-index: 2;
	
	.priority-urgent & {
		background-color: $urgent-red;
	}
	
	.priority-high & {
		background-color: $high-orange;
	}
	
	.priority-medium & {
		background-color: $medium-purple;
	}
	
	.priority-low & {
		background-color: $low-gray;
	}
}

.tags-container {
	position: absolute;
	top: $spacing-lg;
	left: $spacing-lg;
	display: flex;
	flex-wrap: wrap;
	gap: $spacing-xs;
	pointer-events: auto;
}

.tag {
	padding: 2px $spacing-sm;
	background-color: $primary-light-blue;
	color: $primary-blue;
	font-size: $font-size-caption;
	border-radius: $border-radius-lg;
}

.meta-info-container {
	position: absolute;
	bottom: $spacing-lg;
	right: $spacing-lg;
	display: flex;
	align-items: center;
	gap: $spacing-xs;
	pointer-events: auto;
}

.priority-tag {
	padding: 2px $spacing-sm;
	border-radius: $border-radius-lg;
	
	&.priority-urgent {
		background-color: $urgent-light-red;
		
		.priority-text {
			color: $urgent-red;
		}
	}
	
	&.priority-high {
		background-color: $high-light-orange;
		
		.priority-text {
			color: $high-orange;
		}
	}
	
	&.priority-medium {
		background-color: $medium-light-purple;
		
		.priority-text {
			color: $medium-purple;
		}
	}
	
	&.priority-low {
		background-color: $low-light-gray;
		
		.priority-text {
			color: $low-gray;
		}
	}
}

.priority-text {
	font-size: $font-size-caption;
	font-weight: $font-weight-normal;
}

.type-tag {
	padding: 2px $spacing-xs;
	border-radius: $border-radius-sm;
	background-color: $background-gray;
	
	&.task {
		background-color: #E0F2FE;
		
		.type-text {
			color: #0891B2;
		}
	}
	
	&.schedule {
		background-color: #F3E8FF;
		
		.type-text {
			color: #7C3AED;
		}
	}
}

.type-text {
	font-size: 10px;
	font-weight: $font-weight-semibold;
}

.card-actions {
	position: absolute;
	right: -120px; // 初始位置在右侧外面
	top: 0;
	bottom: 0;
	width: 120px;
	display: flex;
	align-items: center;
	justify-content: space-around;
	padding: 0 $spacing-sm;
	transition: right 0.3s ease;
	z-index: 3; // 提高z-index，确保在最上层
	
	.schedule-card.swiped & {
		right: 0; // 滑动时移动到可见位置
	}
	
	&.visible {
		right: 0; // 滑动时移动到可见位置
	}
}

.action-btn {
	width: 40px;
	height: 40px;
	border-radius: 50%;
	border: none;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: transform 0.2s ease, opacity 0.3s ease;
	opacity: 0.9;
	
	&.edit-btn {
		background-color: $primary-blue;
	}
	
	&.delete-btn {
		background-color: $urgent-red;
	}
	
	&:active {
		transform: scale(0.9);
		opacity: 1;
	}
}
</style> 